﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Kooboo.Commerce.Promotions.DiscountByBrand
{
    internal class EnumHelper
    {
        public static IEnumerable<SelectListItem> ConvertEnumToSelectListItem<T>(int? selected)
        {
            List<SelectListItem> selecteItems = new List<SelectListItem>();
            var dictionary = ConvertEnumToDictionary<T>();
            if (dictionary != null)
            {
                foreach (var item in dictionary)
                {
                    selecteItems.Add(new SelectListItem()
                    {
                        Text = item.Key,
                        Value = item.Value.ToString(),
                        Selected = item.Value == (selected ?? -1)
                    });
                }
                return selecteItems;
            }
            else
            {
                return null;
            }
        }

        static IDictionary<String, Int32> ConvertEnumToDictionary<T>()
        {
            if (typeof(T).BaseType != typeof(Enum))
            {
                throw new InvalidCastException();
            }

            return Enum.GetValues(typeof(T)).Cast<Int32>().ToDictionary(currentItem => Enum.GetName(typeof(T), currentItem));
        }
    }
}